package judesart.app.client.pub.gallery.ui;

import java.util.ArrayList;
import java.util.List;

import judesart.app.client.artwork.ArtworkController;
import judesart.app.client.artwork.ArtworkControllerAsync;
import judesart.app.domain.Artwork;
import judesart.app.domain.ArtworkPhoto;

import com.allen_sauer.gwt.log.client.Log;
import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.data.BaseListLoader;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelReader;
import com.extjs.gxt.ui.client.data.ListLoadResult;
import com.extjs.gxt.ui.client.data.ListLoader;
import com.extjs.gxt.ui.client.data.MemoryProxy;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.Composite;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.ListView;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Image;

public class ArtworkPanel extends Composite {
    ArtworkControllerAsync artworkController = ArtworkController.Util.getInstance();

    private final LayoutContainer mainPanel;
    private final Html htmlTitle;
    private final ListView<BeanModel> listViewPhotos;
    private Artwork artwork;
    private final List<ArtworkPhoto> photos = new ArrayList<ArtworkPhoto>();
    private final ListLoader<ListLoadResult<ArtworkPhoto>> loader;
    private final Html htmlInfo;
    private final Image mainImage;

    private final Html htmlFbLike;

    public ArtworkPanel() {
        mainPanel = new LayoutContainer();
        mainPanel.setLayout(new RowLayout(Orientation.VERTICAL));
        mainPanel.setSize("100%", "650px");
        mainPanel.setId("id-jaw-ArtworkPanel");

        MemoryProxy<List<ArtworkPhoto>> proxy = new MemoryProxy<List<ArtworkPhoto>>(photos);
        loader = new BaseListLoader<ListLoadResult<ArtworkPhoto>>(proxy, new BeanModelReader());
        ListStore<BeanModel> store = new ListStore<BeanModel>(loader);
        loader.load();

        mainImage = new Image((String) null);
        mainImage.getElement().setId("id-jaw-ArtworkPanel-image");
        mainPanel.add(mainImage);

        htmlTitle = new Html("Loading...");
        htmlTitle.setTagName("div");
        htmlTitle.setId("id-jaw-ArtworkPanel-title");
        mainPanel.add(htmlTitle);
        htmlInfo = new Html();
        htmlInfo.setTagName("div");
        htmlInfo.setId("id-jaw-ArtworkPanel-info");
        mainPanel.add(htmlInfo);
        htmlFbLike = new Html();
        htmlFbLike.setTagName("div");
        mainPanel.add(htmlFbLike);

        listViewPhotos = new ListView<BeanModel>(store) {
            @Override
            protected BeanModel prepareData(BeanModel model) {
                ArtworkPhoto g = model.getBean();
                return model;
            }
        };
        listViewPhotos.setLoadingText("loading...");
        listViewPhotos.setBorders(false);
        listViewPhotos.setWidth(600);
        listViewPhotos.setTemplate(getTemplate());
        listViewPhotos.setItemSelector("div.thumb-wrap");
        listViewPhotos.getSelectionModel().addListener(Events.SelectionChange,
                new Listener<SelectionChangedEvent<BeanModel>>() {
                    public void handleEvent(SelectionChangedEvent<BeanModel> be) {
                        onSelectionChanged(be);
                    }
                });
        listViewPhotos.setId("id-jaw-ArtworkPanel-photos");
        mainPanel.add(listViewPhotos);

        initComponent(mainPanel);
    }

    public void openArtwork(Long artworkId) {
        artworkController.getArtwork(artworkId, new AsyncCallback<Artwork>() {
            @Override
            public void onFailure(Throwable caught) {
                Log.error("Unable to get artwork", caught);
            }

            @Override
            public void onSuccess(Artwork result) {
                setArtwork(result);
            }
        });
    }

    private void setArtwork(Artwork artwork) {
        this.artwork = artwork;
        photos.clear();
        if (this.artwork.getPhotos() != null) {
            photos.addAll(this.artwork.getPhotos());
        }
        htmlTitle.setHtml(artwork.getTitle() + "<span> @ "
                + Long.toString(artwork.getYear()) + "</span>");
        htmlInfo.setHtml("<span id='id-jaw-ArtworkPanel-dimensions'>"
                + artwork.getDimensions()
                + " cm</span><span id='id-jaw-ArtworkPanel-technic'> ("
                + artwork.getTechnic() + ")</span>");
        String fb = "<iframe src=\"http://www.facebook.com/plugins/like.php?locale=en_EN&href=http%3A%2F%2Fwww.judithshaylor.com%2F%23gallery%2Fartwork%2F"
                + artwork.getId()
                + "&amp;layout=standard&amp;show_faces=true&amp;width=400&amp;action=like&amp;font=trebuchet+ms&amp;colorscheme=light&amp;height=80\" scrolling=\"no\" frameborder=\"0\" style=\"border:none; overflow:hidden; width:450px; height:80px;\" allowTransparency=\"true\"></iframe>";
        htmlFbLike.setHtml(fb);
        if (photos.size() > 0) {
            mainImage.setUrl("/image?id=" + photos.get(0).getImageId()
                    + "&size=600x600");
        }
        listViewPhotos.hide();
        loader.load();
        mainPanel.layout();
    }

    private native String getTemplate() /*-{
        return ['<tpl for=".">', 
        '<div style="float:left;margin:2em 0 2em 2em; padding:2px;width:24px; height: 24px;" class="thumb-wrap" id="{imageId}">', 
        '<div style="width: 100%;" class="thumb"><img src="/image?id={imageId}&size=24x24&crop=true"></div>', 
        '</div>',
        '</tpl>', 
        '<div class="x-clear"></div>'].join("");
    }-*/;

    private void onSelectionChanged(SelectionChangedEvent<BeanModel> be) {
        Object source = be.getSource();
        Log.debug("source [" + source + "]");
        if (be.getSelection().size() == 0) {
            return;
        }
        final BeanModel model = be.getSelection().get(0);
        ArtworkPhoto photo = model.getBean();
        // openRoom(room);
    }
}
